# -*- coding:utf-8 -*-
from django.shortcuts import render
from toolkit.pre_load import pre_load_thu
from toolkit.pre_load import neo_con
from Model.neo_models import Neo4j
import random
import re

thu_lac = pre_load_thu
db = neo_con

# 1.Phe_has_Cause
# 2.Phe_has_Mnt
# 3.Cause_lead_Phe
# 4.Mnt_to_Phe
# 5.Mnt_has_Cause
pattern = [[r"故障[\u4e00-\u9fa5]+的原因是什么", r"有哪些原因产生[\u4e00-\u9fa5]+故障",r"[\u4e00-\u9fa5]+的原因有哪些"],
           [r"针对[\u4e00-\u9fa5]+有哪些解决办法", r"故障[\u4e00-\u9fa5]+有哪些维护方法", r"有哪些方法可以解决[\u4e00-\u9fa5]+故障",
            r"故障[\u4e00-\u9fa5]+的维护措施", r"维护方法", r"维护措施"],
           [r"造成哪些影响", r"产生哪些故障现象", r"[\u4e00-\u9fa5]+会有哪些影响"],
           [r"[\u4e00-\u9fa5]+可以解决哪些问题", r"可以预防的故障现象有哪些", r"可以解决哪些故障问题"],
           [r"[\u4e00-\u9fa5]+方法主要针对哪些故障原因", r"维护方法[\u4e00-\u9fa5]+故障原因"]]



# 1.根据故障现象进行模糊查询故障原因 Phe_has_Cause
def getCauseByPhe(phe, ret_dict):
    answer = db.getCauseByPhe(phe)
    print("answer:" + str(len(answer)))
    if (len(answer) > 0):
        # 结果数大于6则随机取6个
        if (len(answer) > 6):
            selected_index = []
            n = len(answer)
            m = 6
            for i in range(n):
                rand = random.randint(0, n - i - 1)
                if (rand < m):
                    m -= 1
                    selected_index.append(i)
        else:
            selected_index = [i for i in range(len(answer))]
        for index in selected_index:
            cause = answer[index]['n2']['title']
            if (ret_dict.get('list') is None):
                ret_dict['list'] = [
                    {'entity1': phe, 'rel': '有原因', 'entity2': cause, 'entity1_type': '主语', 'entity2_type': '元素'}]
            else:
                ret_dict['list'].append(
                    {'entity1': phe, 'rel': '含有', 'entity2': cause, 'entity1_type': '主语', 'entity2_type': '元素'})

            if (ret_dict.get('answer') is None):
                ret_dict['answer'] = [cause]
            else:
                ret_dict['answer'].append(cause)
    # 将所有的故障原因作为answer返回
    return ret_dict


def question_answering(request):  # index页面需要一开始就加载的内容写在这里
    context = {'ctx': ''}
    if (request.GET):
        question = request.GET['question']
        print(question)
        # 使用thulac进行中文分词
        cut_statement = thu_lac.cut(question, text=False)
        print(cut_statement)
        question_name = ""
        ret_dict = {}

        pos = -1
        q_type = -1
        # 这里修改为使用朴素贝叶斯进行问句类型的分类
        for i in range(len(pattern)):
            for x in pattern[i]:
                # 匹配问句类型
                index = re.search(x, question)
                print("index=" + str(index))
                # 在某一类中找到匹配项之后
                if (index):
                    pos = index.span()[0]
                    q_type = i
                    print("pos = " + str(pos) + " q_type = " + str(q_type))
                    break
            # 找到匹配项之后跳出循环
            if (pos != -1):
                break
        print(pos)

        # 匹配问题，Phe_has_Cause，产生故障现象的原因有哪些
        zhuyu = ""
        if (q_type == 0):
            index = 0
            for x in cut_statement:
                # 找到匹配的第一个字时跳出循环
                if (index > pos):
                    break
                index += len(x)
                # 找到匹配的主语，这里应该是识别出故障现象
                if (x[1] == 'n'):
                    zhuyu = zhuyu + x[0]

            if (len(zhuyu) > 0):
                # ret_dict = getCauseByPhe(zhuyu, ret_dict)
                ret_dict = getCauseByPhe("变色", ret_dict)
        print(ret_dict)

        if (len(ret_dict) != 0 and ret_dict != 0):
            return render(request, 'question_answering.html', {'ret': ret_dict})
        print(context)
        return render(request, 'question_answering.html', {'ctx': '暂时找不到答案'})
    # return render(request, 'question_answering.html', context)
    return render(request, 'question_answering.html', {'ctx' : question_type})
